package com.service.impl;

import com.domain.Employee;
import com.mapper.EmployeeMapper;
import com.qo.PageResult;
import com.qo.QueryObject;
import com.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;


@Transactional
@Service
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private EmployeeMapper mapper;

    @Override
    public void delete(Long id) {
        mapper.deleteRelation(id);
        mapper.deleteByPrimaryKey(id);
    }

    @Override
    public void save(Employee employee, Long[] roleIds) {
        //保存之后employee就会有id
        mapper.insert(employee);
        //然后根据id插入
        if (roleIds != null && roleIds.length > 0) {
            for (Long roleId : roleIds) {
                mapper.insertRelation(employee.getId(),roleId);
            }
        }
    }

    @Override
    public Employee get(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Employee> listAll() {
        return mapper.selectAll();
    }

    @Override
    public void update(Employee employee, Long[] roleIds) {
        mapper.updateByPrimaryKey(employee);
        //删除关系
        mapper.deleteRelation(employee.getId());

        if (roleIds != null && roleIds.length > 0) {
            //关联关系
            for (Long roleId : roleIds) {
                mapper.insertRelation(employee.getId(),roleId);
            }
        }
    }

    @Override
    public PageResult<Employee> query(QueryObject qo) {
        int count = mapper.selectForCournt(qo);
        if (count == 0){
            new PageResult<>(count);
            //new PageResult<>(qo.getCurrentPage(), count, Collections.emptyList(), qo.getPageSize());
        }
        //当查询有数据时
        List<Employee> list = mapper.selectLimitList(qo);
        return new PageResult<>(qo.getCurrentPage(),count,list,qo.getPageSize());
    }

    @Override
    public Employee login(String username, String password) {
        //判空
        //if (username == null || username.length() <= 0)
        if (!StringUtils.hasText(username)){  //org.springframework.util.StringUtils
            throw new RuntimeException("用户名不可为空");
        }
        if (!StringUtils.hasText(password)){
            throw new RuntimeException("密码不可为空");
        }
        //查询数据库中是否有匹配的数据
        Employee employee = mapper.selectByUsernameAndPassword(username, password);
        if(employee==null){
            //通知调用者出现异常
            throw new RuntimeException("账号和密码不匹配");
        }
        return employee;
    }

    @Override
    public void updatePassword(Employee employee) {
        mapper.updatePasswordById(employee);
    }
}
